using System.Linq;
using Tools.Domain.Common.Repositories.Contracts;
using Tools.Domain.Specifications;
using Webshop20.Application.Common;
using Webshop20.Application.DataTransferObjects;
using Webshop20.Application.Queries.Messages;
using Webshop20.Domain.Shared.Products.Core;
using Webshop20.Domain.Shared.Products.Specifications;
using Tools.Domain.Specifications.Creation;

namespace Webshop20.Application.Queries.Services
{
    public class GetProductsByFullTextSearchService : IGetProductsByFullTextSearchService
    {
        private AntiCorruptionLayers.Lucene.IProductFullTextSearchService searchService;
        private IRepository<Product> productsRepository;
        private ISpecificationFactory specificationFactory;
        

        public GetProductsByFullTextSearchService(AntiCorruptionLayers.Lucene.IProductFullTextSearchService searchService, IRepository<Product> products, ISpecificationFactory specificationFactory)
        {
            this.searchService = searchService;
            this.specificationFactory = specificationFactory;
            this.productsRepository = products;
        }

        public ISystemMessage Handle(ISystemMessage request)
        {
            var productFullTextSearchRequest = request as ProductFullTextSearchRequest;
            var ids = searchService.LookForProductsWith(productFullTextSearchRequest.SearchTerm);
            ISpecification<Product> productsAreInFulltextResultSpec =
                specificationFactory.Create<Product, ProductsAreInArraySpecification>(ids);
            var products = productsRepository
                            .FindBySpecification(productsAreInFulltextResultSpec)
                            .Select(x=>AutoMapper.Mapper.Map(x, typeof(Product), typeof(ProductDTO)) as ProductDTO )
                            .ToPagedList(productFullTextSearchRequest.Page - 1, productFullTextSearchRequest.PageSize);

            return new ProductFullTextSearchResponse(productFullTextSearchRequest.SearchTerm,
                                                     productFullTextSearchRequest.Page,
                                                     productFullTextSearchRequest.PageSize, products);
       
        }
    }
}